using Newtonsoft.Json;
using AdminApiTemplate.Common.Exceptions;
using System.Net.Http.Headers;
using System.Text;

namespace AdminApiTemplate.Common.Helpers
{
    public class HttpHelper
    {
        public static Tout Get<Tout>(string url)
        {
            return Get<Tout>(url, null);
        }

        public static Tout Get<Tout>(string url, Dictionary<string, string> headers)
        {
            var sb = new StringBuilder();
            sb.AppendLine($"GET:{url}");

            var handler = new HttpClientHandler();
            handler.ServerCertificateCustomValidationCallback = (message, cert, chain, error) => true;

            var client = new HttpClient(handler);
            var message = new HttpRequestMessage(HttpMethod.Get, url);

            if (headers!=null && headers.Count>0)
            {
                foreach (var key in headers.Keys)
                {
                    message.Headers.Add(key, headers[key]);
                }
            }

            var result = client.Send(message);
            if (!result.IsSuccessStatusCode)
            {
                sb.AppendLine($"{(int)result.StatusCode} {result.StatusCode}");
                LogHelper.WriteAsync(sb.ToString(), "Request");
                throw new WithCodeException((int)ErrorCodeEnum.CodeError, "获取数据失败，接口异常");
            }

            var bytes = result.Content.ReadAsByteArrayAsync().Result;
            var rspJson = Encoding.UTF8.GetString(bytes);
            sb.AppendLine($"Rsp:{rspJson}");

            var rsp = JsonConvert.DeserializeObject<Tout>(rspJson);
            if (rsp==null)
            {
                LogHelper.WriteAsync(sb.ToString(), "Request");
                throw new WithCodeException((int)ErrorCodeEnum.CodeError, "获取数据失败，接口异常");
            }

            LogHelper.WriteAsync(sb.ToString(), "Request");
            return rsp;
        }

        public static string Get(string url)
        {
            return Get(url, null);
        }

        public static string Get(string url, Dictionary<string, string> headers)
        {
            var sb = new StringBuilder();
            sb.AppendLine($"GET:{url}");

            var handler = new HttpClientHandler();
            handler.ServerCertificateCustomValidationCallback = (message, cert, chain, error) => true;

            var client = new HttpClient(handler);
            var message = new HttpRequestMessage(HttpMethod.Get, url);

            if (headers!=null && headers.Count>0)
            {
                foreach (var key in headers.Keys)
                {
                    message.Headers.Add(key, headers[key]);
                }
            }

            var result = client.Send(message);
            if (!result.IsSuccessStatusCode)
            {
                sb.AppendLine($"{(int)result.StatusCode} {result.StatusCode}");
                LogHelper.WriteAsync(sb.ToString(), "Request");
                throw new WithCodeException((int)ErrorCodeEnum.CodeError, "获取数据失败，接口异常");
            }

            var bytes = result.Content.ReadAsByteArrayAsync().Result;
            var rspJson = Encoding.UTF8.GetString(bytes);
            sb.AppendLine($"Rsp:{rspJson}");
            LogHelper.WriteAsync(sb.ToString(), "Request");
            return rspJson;
        }

        public static Tout Post<Tin, Tout>(string url, Tin req)
        {
            return Post<Tin, Tout>(url, req, null);
        }

        public static Tout Post<Tin, Tout>(string url, Tin req, Dictionary<string, string> headers)
        {
            var sb = new StringBuilder();
            sb.AppendLine($"POST:{url}");

            var reqJson = JsonConvert.SerializeObject(req);
            var handler = new HttpClientHandler();
            handler.ServerCertificateCustomValidationCallback = (message, cert, chain, error) => true;

            var client = new HttpClient(handler);
            var message = new HttpRequestMessage(HttpMethod.Post, url);
            message.Content= new StringContent(reqJson);
            message.Content.Headers.ContentType=new MediaTypeHeaderValue("application/json");
            sb.AppendLine($"Req:{reqJson}");

            if (headers!=null && headers.Count>0)
            {
                foreach (var key in headers.Keys)
                {
                    if (key=="ContentType")
                    {
                        continue;
                    }
                    message.Content.Headers.Add(key, headers[key]);
                }
            }

            var result = client.Send(message);
            if (!result.IsSuccessStatusCode)
            {
                sb.AppendLine($"{(int)result.StatusCode} {result.StatusCode}");
                LogHelper.WriteAsync(sb.ToString(), "Request");
                throw new WithCodeException((int)ErrorCodeEnum.CodeError, "获取数据失败，接口异常");
            }

            var bytes = result.Content.ReadAsByteArrayAsync().Result;
            var rspJson = Encoding.UTF8.GetString(bytes);
            sb.AppendLine($"Rsp:{rspJson}");

            var rsp = JsonConvert.DeserializeObject<Tout>(rspJson);
            if (rsp==null)
            {
                LogHelper.WriteAsync(sb.ToString(), "Request");
                throw new WithCodeException((int)ErrorCodeEnum.CodeError, "获取数据失败，接口异常");
            }

            LogHelper.WriteAsync(sb.ToString(), "Request");
            return rsp;
        }

        public static Tout Post<Tout>(string url, Dictionary<string, string> data, Dictionary<string, string> headers)
        {
            var sb = new StringBuilder();
            sb.AppendLine($"POST:{url}");

            var reqJson = JsonConvert.SerializeObject(data);
            var handler = new HttpClientHandler();
            handler.ServerCertificateCustomValidationCallback = (message, cert, chain, error) => true;

            var client = new HttpClient(handler);
            var message = new HttpRequestMessage(HttpMethod.Post, url);
            message.Content= new FormUrlEncodedContent(data);
            sb.AppendLine($"Req:{reqJson}");

            if (headers!=null && headers.Count>0)
            {
                foreach (var key in headers.Keys)
                {
                    if (key=="ContentType")
                    {
                        continue;
                    }
                    message.Content.Headers.Add(key, headers[key]);
                }
            }

            var result = client.Send(message);
            if (!result.IsSuccessStatusCode)
            {
                sb.AppendLine($"{(int)result.StatusCode} {result.StatusCode}");
                LogHelper.WriteAsync(sb.ToString(), "Request");
                throw new WithCodeException((int)ErrorCodeEnum.CodeError, "获取数据失败，接口异常");
            }

            var bytes = result.Content.ReadAsByteArrayAsync().Result;
            var rspJson = Encoding.UTF8.GetString(bytes);
            sb.AppendLine($"Rsp:{rspJson}");

            var rsp = JsonConvert.DeserializeObject<Tout>(rspJson);
            if (rsp==null)
            {
                LogHelper.WriteAsync(sb.ToString(), "Request");
                throw new WithCodeException((int)ErrorCodeEnum.CodeError, "获取数据失败，接口异常");
            }

            LogHelper.WriteAsync(sb.ToString(), "Request");
            return rsp;
        }
    }
}
